﻿using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Events;
using StarryEdge.Core.Tool;
using StarryEdge.Menu.SettingSystem.Model;
using StarryEdge.Menu.SettingSystem.ViewModels.Dialog;
using StarryEdge.Menu.SettingSystem.Views.Dialog;
using StarryEdge.WPF.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Xml.Linq;

namespace StarryEdge.Menu.SettingSystem.ViewModels
{
    public class LanguageDictionaryViewModel : Prism.Mvvm.BindableBase
    {
        public ObservableCollection<StarryEdge.Core.Models.LanguageFileInfoModel> LangList { get; set; }
        public ObservableCollection<LanguageInfoModel> ToolTipItems { get; set; }
        public ObservableCollection<LanguageInfoModel> LangItems { get; set; }
        private string _path = Path.Combine(Environment.CurrentDirectory, "lang", "languagefileinfo.json");
        private StarryEdge.Core.IDialogHost _dialogHost;
        private IEventAggregator _aggregator;
        public LanguageDictionaryViewModel(StarryEdge.Core.IDialogHost dialogHost, IEventAggregator aggregator)
        {
            _aggregator = aggregator;
            _dialogHost = dialogHost;
            LangItems = new ObservableCollection<LanguageInfoModel>();
            ToolTipItems = new ObservableCollection<LanguageInfoModel>();
            if (File.Exists(_path))
            {
                string str = File.ReadAllText(_path, Encoding.UTF8);
                LangList = System.Text.Json.JsonSerializer.Deserialize<ObservableCollection<StarryEdge.Core.Models.LanguageFileInfoModel>>(str);
            }
            else
            {
                LangList = new ObservableCollection<StarryEdge.Core.Models.LanguageFileInfoModel>();
            }
            if (LangList.Count > 0)
            {
                _editLang = LangList[0];
                _referLang = LangList[0];
                string[] strs = File.ReadAllLines(Path.Combine(Environment.CurrentDirectory, "lang", $"{LangList[0].Lang}.lang"));
                foreach (string str in strs)
                {
                    if (string.IsNullOrEmpty(str))
                    {
                        continue;
                    }
                    string[] l = str.Split('=');
                    LangItems.Add(new LanguageInfoModel()
                    {
                        AnotherName = l[0],
                        Exhibition = l[1],
                        Refer = l[1]
                    });
                }
                strs = File.ReadAllLines(Path.Combine(Environment.CurrentDirectory, "lang", $"{LangList[0].ToolTip}.tip"));
                foreach (string str in strs)
                {
                    if (string.IsNullOrEmpty(str))
                    {
                        continue;
                    }
                    string[] l = str.Split('=');
                    ToolTipItems.Add(new LanguageInfoModel()
                    {
                        AnotherName = l[0],
                        Exhibition = l[1],
                        Refer = l[1]
                    });
                }
            }
        }

        public DelegateCommand Delete => new DelegateCommand(() =>
        {

        });

        public DelegateCommand Save => new DelegateCommand(() =>
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in LangItems)
                {
                    sb.AppendLine($"{item.AnotherName}={item.Exhibition}");
                }
                File.WriteAllText(Path.Combine(Environment.CurrentDirectory, "lang", $"{EditLang.Lang}.lang"), sb.ToString(), Encoding.UTF8);
                sb.Clear();
                foreach (var item in ToolTipItems)
                {
                    sb.AppendLine($"{item.AnotherName}={item.Exhibition}");
                }
                File.WriteAllText(Path.Combine(Environment.CurrentDirectory, "lang", $"{EditLang.Lang}.tip"), sb.ToString(), Encoding.UTF8);
                File.WriteAllText(_path, System.Text.Json.JsonSerializer.Serialize(LangList, OptionsHelper.Options), Encoding.UTF8);
                _dialogHost?.DialogShow("保存成功", Core.Enums.LogLevel.Success);
            }
            catch (Exception ex)
            {
                _dialogHost?.DialogShow($"保存异常：{ex}", Core.Enums.LogLevel.Error);
            }
        });

        private void UpdateLang(string value, bool isEdit = false)
        {
            string[] strings = value.Split('=');
            var lm = LangItems.FirstOrDefault(x => x.AnotherName == strings[0]);
            if (lm != null)
            {
                if (isEdit)
                {
                    lm.Refer = strings[1];
                }
                else
                {
                    lm.Exhibition = strings[1];
                }
            }
        }

        private void UpdateToolTip(string value, bool isEdit = false)
        {
            string[] strings = value.Split('=');
            var lm = ToolTipItems.FirstOrDefault(x => x.AnotherName == strings[0]);
            if (lm != null)
            {
                if (isEdit)
                {
                    lm.Refer = strings[1];
                }
                else
                {
                    lm.Exhibition = strings[1];
                }
            }
        }

        public DelegateCommand New => new DelegateCommand(() =>
        {
            if (DialogHost.IsDialogOpen("Global")) DialogHost.Close("Global");
            DialogHost.Show(new NewLanguage()
            {
                DataContext = new NewLanguagePopupDialog(this)
            }, "Global");
        });

        public void SaveLangInfo()
        {
            foreach (var tooltip in ToolTipItems)
            {
                tooltip.Exhibition = default;
            }
            foreach (var lang in LangItems)
            {
                lang.Exhibition = default;
            }
            File.WriteAllText(_path, System.Text.Json.JsonSerializer.Serialize(LangList, OptionsHelper.Options), Encoding.UTF8);
            MessageEventModel message = new MessageEventModel
            {
                Code = 240,
                Message = "UpdateLanguageInfo",
            };
            _aggregator.GetEvent<MessageEvent>().Publish(message);
        }

        private StarryEdge.Core.Models.LanguageFileInfoModel _referLang;
        public StarryEdge.Core.Models.LanguageFileInfoModel ReferLang
        {  get => _referLang; 
            set 
            {
                _referLang = value;
                string[] strs = File.ReadAllLines(Path.Combine(Environment.CurrentDirectory, "lang", $"{_referLang.Lang}.lang"));
                foreach (var item in strs)
                {
                    UpdateLang(item, true);
                }
                strs = File.ReadAllLines(Path.Combine(Environment.CurrentDirectory, "lang", $"{_referLang.ToolTip}.tip"));
                foreach (var item in strs)
                {
                    UpdateToolTip(item, true);
                }
            } 
        }

        private StarryEdge.Core.Models.LanguageFileInfoModel _editLang;

        public StarryEdge.Core.Models.LanguageFileInfoModel EditLang
        {
            get { return _editLang; }
            set { 
                SetProperty(ref _editLang, value);
                string path = Path.Combine(Environment.CurrentDirectory, "lang", $"{_editLang.Lang}.lang");
                if (File.Exists(path))
                {
                    string[] strs = File.ReadAllLines(path);
                    foreach (var item in strs)
                    {
                        UpdateLang(item);
                    }
                }
                else
                {
                    foreach (var lang in LangItems)
                    {
                        lang.Exhibition = default;
                    }
                }
                path = Path.Combine(Environment.CurrentDirectory, "lang", $"{_editLang.ToolTip}.tip");
                if (File.Exists(path)) { 
                    string[] strs = File.ReadAllLines(path);
                    foreach (var item in strs)
                    {
                        UpdateToolTip(item);
                    }
                }
                else
                {
                    foreach (var tooltip in ToolTipItems)
                    {
                        tooltip.Exhibition = default;
                    }
                }
            }
        }

    }
}
